<?php

namespace App\Repository;

use App\Consts\GlobalConst;
use App\Models\IndexComment;
use App\Models\Select\ReplySelect;
use App\Models\SysComment;
use App\Models\SysReply;

/**
 * @package App\Repository
 * @see ReplyRepository
 */
class ReplyRepository extends BaseRepository
{
    /**
     * 获取评论下的回复列表
     * @param $commentId
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function getRepliesByCommentId($commentId)
    {
        $provider = SysReply::getInstance($commentId)
            ->where('comment_id', $commentId)
            ->where('is_deleted', GlobalConst::IS_NOT_DELETE);

        $provider->orderBy('created_at', GlobalConst::ORDER_TYPE_DESC);

        return $this->setPagination($provider);
    }

    /**
     * 新增回复
     * @param $loadData
     * @return SysReply|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model
     */
    public function createReply($loadData)
    {
        return SysReply::getModel($loadData['comment_id'])->create($loadData);
    }

    /**
     * 删除回复
     * @param SysReply $reply
     * @return SysComment
     */
    public function deleteReply($reply): bool
    {
        return $reply
            ->update(['is_deleted' => GlobalConst::IS_DELETED]);
    }

    /**
     * 【暂时】删除索引表记录
     * @param SysReply $reply
     * @return bool
     */
    public function deleteIndexComment($reply): bool
    {
        return $reply->indexComment::getInstance()
            ->where('reply_id', $reply['reply_id'])
            ->update(['is_deleted' => GlobalConst::IS_DELETED]);
    }

    /**
     * 判断评论下是否有回复
     * @param $commentId
     * @return bool
     */
    public function judgeCommentHaveNormalReply($commentId)
    {
        $replies = SysReply::getInstance($commentId)
            ->select(['id'])
            ->where('comment_id', $commentId)
            ->where('is_deleted', GlobalConst::IS_NOT_DELETE)
            ->get();
        return $replies->toArray() ? true : false;
    }

    /**
     * 通过【回复ID】获取评论
     * @param string $replyId
     * @param string $selectScene
     * @return \Illuminate\Database\Eloquent\Builder|SysReply|object|null
     */
    public function getReplyByReplyId($replyId, $selectScene = ReplySelect::SELF_DETAIL)
    {
        $indexComment = IndexComment::getModel()
            ->select(['comment_id'])
            ->where('reply_id', $replyId)
            ->first();
        if (!$indexComment) {
            return null;
        }

        return SysReply::getInstance($indexComment->comment_id)
            ->select(ReplySelect::getSelects($selectScene))
            ->where('reply_id', $replyId)
            ->first();
    }
}
